package com.mk.remotelog;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 设置远程日志
 */
public class LogClient {
    public static String defaultHost = "localhost";

    public static Integer defaultPort = 8080;

    public static void setSystemPrintStream() throws IOException {
        setSystemPrintStream(defaultHost, defaultPort);
    }

    public static void setSystemError() throws IOException {
        setSystemError(defaultHost, defaultPort);
    }

    private static PrintStream connectSocket(String host,Integer port) throws IOException{
        // 连接socket服务器
        Socket localhost = new Socket(host, port);
        OutputStream outputStream = localhost.getOutputStream();
        return new PrintStream(outputStream);
    }

    public static void setSystemPrintStream(String host,Integer port) throws IOException {
        // 设置print的输出流
        System.setOut(connectSocket(host,port));
    }

    public static void setSystemError(String host,Integer port) throws IOException {
        // 设置报错信息的输出流
        System.setErr(connectSocket(host,port));
    }

    /**
     * 使用默认host和port
     * @throws IOException
     */
    public static void setRemoteConsole() throws IOException {
        setRemoteConsole(defaultHost,defaultPort);
    }

    /**
     * 设置输出和报错信息打印为远程打印
     * @param host
     * @param port
     * @throws IOException
     */
    public static void setRemoteConsole(String host,Integer port) throws IOException {
        PrintStream printStream = connectSocket(host, port);
        System.setOut(printStream);
        System.setErr(printStream);
    }
}
